package routers

import (
	"io/ioutil"
	"ruoyi-go/app/admin"
	"ruoyi-go/app/html"
	"ruoyi-go/config"
	_ "ruoyi-go/docs"
	"ruoyi-go/pkg/logs"
	"ruoyi-go/utils"
	error2 "ruoyi-go/utils/error"
	"strings"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

// Init 初始化
func Init() *gin.Engine {
	gin.SetMode(config.Server.RunMode)
	r := gin.New()

	// 如果URL的路径是固定的，那么重定向到配置的固定路径
	r.RedirectFixedPath = true

	r.Use(logs.Logger())
	r.Use(gin.Recovery())
	/*自定义错误*/
	r.Use(error2.Recover)

	// 设置信任网络 []string
	// nil 为不计算，避免性能消耗，上线应当设置
	_ = r.SetTrustedProxies(nil)

	r.Use(utils.Core())
	r.HTMLRender = createRender()

	r.Static("/profile", "./static/images")
	r.Static("/admin", "./view/admin")
	r.Static("/static", "./view/mobile/static")
	r.Static("/favicon.ico", "./view/admin/static/favicon.ico")

	if config.Server.EnabledSwagger {
		r.GET("/swagger/*any", func(c *gin.Context) {
			ginSwagger.DisablingWrapHandler(swaggerFiles.Handler, "SWAGGER")(c)
		})
	}

	// 关键点【解决页面刷新404的问题】
	// 404 NotFound
	r.NoRoute(func(c *gin.Context) {
		accept := c.Request.Header.Get("Accept")
		flag := strings.Contains(accept, "text/html")
		if flag {
			content, err := ioutil.ReadFile("view/admin/index.html")
			if (err) != nil {
				c.Writer.WriteHeader(404)
				c.Writer.WriteString("Not Found")
				return
			}
			c.Writer.WriteHeader(200)
			c.Writer.Header().Add("Accept", "text/html")
			c.Writer.Write((content))
			c.Writer.Flush()
		}
	})

	// 加载多个APP的路由配置
	html.Routers(r)
	admin.Routers(r)

	return r
}

// 不同模板设置
func createRender() multitemplate.Renderer {
	p := multitemplate.NewRenderer()
	p.AddFromFiles("admin", "view/admin/index.html")
	p.AddFromFiles("mobile", "view/mobile/index.html")
	p.AddFromFiles("mobile_old", "view/mobile_old/index.html")
	p.AddFromFiles("protocol", "view/template/protocol.tmpl")
	return p
}
